import { StrictMode, useEffect, useState } from "react";
import LicensePage from "./LicensePage.tsx";
import CodePage from "./CodePage.tsx";
import CodeGenPage from "./CodeGenPage.tsx";
import { BrowserRouter, Routes, Route } from "react-router";

const development = import.meta.env.DEV;

function useMediaQuery(query: string) {
  const [match, setMatch] = useState<boolean>(false);
  useEffect(() => {
    const queryList = globalThis.matchMedia(query);
    setMatch(queryList.matches);
    const change = (event: MediaQueryListEvent) => {
      setMatch(event.matches);
    };
    queryList.addEventListener("change", change);
    return () => {
      queryList.removeEventListener("change", change);
    };
  }, [query]);
  return match;
}

function App() {
  const isDark = useMediaQuery("(prefers-color-scheme: dark)");

  useEffect(() => {
    if (isDark) {
      document.documentElement.classList.replace(
        "mdui-theme-light",
        "mdui-theme-dark",
      );
    } else {
      document.documentElement.classList.replace(
        "mdui-theme-dark",
        "mdui-theme-light",
      );
    }
  }, [isDark]);

  return (
    <StrictMode>
      <BrowserRouter basename={development ? "/" : "/page/code-share-page/"}>
        <Routes>
          <Route index element={<CodeGenPage />} />
          <Route path="licenses" element={<LicensePage />} />
          <Route path="code" element={<CodePage dark={isDark} />} />
        </Routes>
      </BrowserRouter>
    </StrictMode>
  );
}

export default App;
